package com.yan.furns.web.servlet;
import com.yan.furns.entity.Cart;
import com.yan.furns.entity.CartItem;
import com.yan.furns.entity.Furn;
import com.yan.furns.service.FurnService;
import com.yan.furns.service.impl.FurnServiceImpl;
import com.yan.furns.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Yzb
 * @version 1.0
 */
public class CartServlet extends BasicServlet {
	private FurnService furnService = new FurnServiceImpl();
	protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer id = DataUtils.parseInt(req.getParameter("id"), 0);
		Furn furn = furnService.queryFurn(id);
		// todo
		if (furn == null) {
			return;
		}

		CartItem item = new CartItem(id, furn.getName(), 1, furn.getPrice(), furn.getPrice());
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
		cart.addItem(item);
//		System.out.println(cart);

		resp.sendRedirect(req.getHeader("referer"));
	}

	protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer id = DataUtils.parseInt(req.getParameter("id"), 0);
		Integer count = DataUtils.parseInt(req.getParameter("count"), 0);
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
//		System.out.println("id:" + id);
//		System.out.println("count:" + count);

		cart.updateCount(id, count);
		resp.sendRedirect(req.getHeader("Referer"));
	}

	protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer id = DataUtils.parseInt(req.getParameter("id"), 0);
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart == null || !cart.getItems().containsKey(id)) {
			resp.sendRedirect(req.getHeader("Referer"));
			return;
		}
		cart.getItems().remove(id);
		resp.sendRedirect(req.getHeader("Referer"));
	}


	protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart != null) {
			cart.clear();
		}
		resp.sendRedirect(req.getHeader("Referer"));
	}
}
